package dbcon

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"night-talk/model"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

// DBregister 注册操作
func DBregister(c *gin.Context, db *gorm.DB) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		d, err := c.GetRawData()
		if err != nil {
			log.Fatalln(err)
		}
		var dat map[string]string
		fmt.Println(string(d))
		err1 := json.Unmarshal(d, &dat)
		if err1 != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg": "输入格式错误",
			})
			c.Abort()
			return
		}
		username = dat["username"]
		password = dat["password"]

		if username == "" || password == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg": "注册失败，用户名或密码不能为空",
			})
			c.Abort()
			return
		}
	}

	u1 := model.User{Name: username, Password: password}

	var users []model.User
	res := db.Where("name = ?", username).Find(&users)
	if res.RowsAffected == 0 {
		// 创建记录
		db.Debug().Create(&u1)
		//输出json结果给调用方
		c.JSON(http.StatusOK, gin.H{
			"msg": "success",
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "注册失败，用户名重复，请重新注册",
		})
	}
}

// DBlogin 登陆操作
func DBlogin(c *gin.Context, db *gorm.DB) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		d, err := c.GetRawData()
		if err != nil {
			log.Fatalln(err)
		}
		var dat map[string]string
		fmt.Println(string(d))
		err1 := json.Unmarshal(d, &dat)
		if err1 != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg": "输入格式错误",
			})
			c.Abort()
			return
		}
		username = dat["username"]
		password = dat["password"]

		if username == "" || password == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg": "登陆失败，用户名或密码不能为空",
			})
			c.Abort()
			return
		}
	}

	var users []model.User
	res := db.Debug().Where("name = ? AND password = ?", username, password).Find(&users)
	if res.RowsAffected == 0 {
		//输出json结果给调用方
		c.JSON(http.StatusBadRequest, gin.H{
			"username": username,
			"password": password,
			"msg":      "登陆失败，用户名或密码错误，请重新登陆",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg":    "success",
			"Name":   users[0].Name,
			"Avatar": users[0].Avatar,
			"Score":  users[0].Scores,
			"ID":     users[0].ID,
		})
	}
}

// DBgetUsersInfo 获取用户所有信息
func DBgetUsersInfo(c *gin.Context, db *gorm.DB) {
	var users []model.User
	db.Debug().Find(&users)
	if len(users) == 0 {
		c.JSON(http.StatusOK, nil)
	} else {
		c.JSON(http.StatusOK, users)
	}
}

// DBgetAUserInfo 获取某个用户信息
func DBgetAUserInfo(c *gin.Context, db *gorm.DB) {
	username := c.Param("username")
	var users model.User
	res := db.Debug().Where("name = ?", username).Find(&users)
	if res.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "该用户不存在",
		})
	} else {
		c.JSON(http.StatusOK, users)
	}
}

// DBpatchAUserInfo 修改某个用户信息
func DBpatchAUserInfo(c *gin.Context, db *gorm.DB) {
	username := c.Param("username")
	username1 := c.PostForm("username")
	password := c.PostForm("password")
	avatar, err := c.FormFile("avatar")
	if err != nil && err.Error() != "http: no such file" {
		c.JSON(http.StatusInternalServerError, gin.H{
			"status":  "failure",
			"message": err.Error(),
		})
		return
	}

	var users model.User
	var users1 model.User
	res := db.Debug().Where("name = ?", username).Find(&users)
	res1 := db.Debug().Where("name=? AND name<>?", username1, username).Find(&users1)
	if res.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "申请改名的用户不存在",
		})
	} else if res1.RowsAffected != 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "该用户名已存在，请尝试其他名字",
		})
	} else {
		var result *gorm.DB
		if err != nil && err.Error() == "http: no such file" {
			result = db.Model(model.User{}).Where("name=?", username).Updates(model.User{Name: username1, Password: password})
		} else {
			result = db.Model(model.User{}).Where("name=?", username).Updates(model.User{Name: username1, Password: password, Avatar: avatar.Filename})
		}
		fmt.Println(result.RowsAffected)
		var users2 model.User
		var res2 *gorm.DB
		if username1 == "" {
			res2 = db.Debug().Where("name=?", username).Find(&users2)
		} else {
			res2 = db.Debug().Where("name=?", username1).Find(&users2)
		}
		if res2.RowsAffected == 0 {
			if username1 != "" {
				c.JSON(http.StatusBadRequest, gin.H{
					"msg": "修改信息失败",
				})
			}
		} else {
			if err != nil && err.Error() != "http: no such file" {
				dst := fmt.Sprintf("./pictures/%s", avatar.Filename)
				fmt.Println("dst:", dst)
				// 上传文件到指定的目录
				err1 := c.SaveUploadedFile(avatar, dst)
				if err1 != nil {
					fmt.Println("文件上传失败")
				}
			} else if err == nil {
				dst := fmt.Sprintf("./pictures/%s", avatar.Filename)
				fmt.Println("dst:", dst)
				// 上传文件到指定的目录
				err1 := c.SaveUploadedFile(avatar, dst)
				if err1 != nil {
					fmt.Println("文件上传失败")
				}
			}
			// fmt.Println("hello")
			c.JSON(http.StatusOK, gin.H{
				"ID":       users2.ID,
				"Name":     users2.Name,
				"Password": users2.Password,
				"Avatar":   users2.Avatar,
				"Score":    users2.Scores,
				"msg":      "success",
			})
		}
	}
}

// DBgetAPicture 获取一张图片
func DBgetAPicture(c *gin.Context, db *gorm.DB) {
	picname := c.Param("picname")
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; ")) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
	c.Writer.Header().Add("Content-Type", "image/jpeg")
	dst := fmt.Sprintf("./pictures/%s", picname)
	c.File(dst)
}

//DBdeductScore 被举报扣分
func DBdeductScore(c *gin.Context, db *gorm.DB) {
	username := c.Param("username")
	var users model.User
	var res *gorm.DB
	res = db.Debug().Where("name=?", username).Find(&users)
	if res.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": "failure",
			"msg":    "无此用户",
		})
		c.Abort()
		return
	}
	result := db.Debug().Model(model.User{}).Where("name=?", username).Updates(model.User{Scores: users.Scores - 10})
	if result.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": "failure",
			"msg":    "举报失败",
		})
		c.Abort()
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"Scores": users.Scores - 10,
		"status": "success",
	})
}
